package com.xhsj.user.pms.oareply.service;

import com.xhsj.user.generalprocess.service.TbPamGeneralProcessTaskService;
import com.xhsj.user.generalprocess.vo.GeneralAuditHistoryVo;
import com.xhsj.user.generalprocess.vo.GeneralAuditVo;
import com.xhsj.user.hr.base.BaseParam;
import com.xhsj.user.hr.system.entity.TbGlobalUser;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.pms.oareply.dto.FindRunTaskDto;
import com.xhsj.user.pms.oareply.entity.TbPamPatentOa;
import com.xhsj.user.pms.oareply.entity.TbPamPatentOaFile;
import com.xhsj.user.pms.oareply.mapper.TbPamPatentOaFileMapper;
import com.xhsj.user.pms.oareply.mapper.TbPamPatentOaMapper;
import com.xhsj.user.pms.oareply.service.TbPamPatentOaService;
import com.xhsj.user.hr.base.BaseService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.pms.oareply.vo.PatentOaAuditVo;
import com.xhsj.user.pms.oareply.vo.PatentOaHiTaskVo;
import com.xhsj.user.pms.oareply.vo.PatentOaRunTaskVo;
import com.xhsj.user.pms.patent.domain.TbPamOverseasApply;
import com.xhsj.user.pms.patent.vo.FindRunTaskVo;
import com.xhsj.user.pms.patent.vo.OverseasApplyAuditVo;
import com.xhsj.user.properties.RoleKeyNameProperites;
import com.xhsj.user.utils.Md5Utils;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.io.Serializable;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import javax.validation.constraints.NotNull;

/**
 * <p>
 * 专利OA答复 服务实现类
 * </p>
 *
 * @author liuqinghua
 * @since Jul 28, 2021 8:04:28 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class TbPamPatentOaService extends BaseService<TbPamPatentOaMapper, TbPamPatentOa>{
    @Autowired
    private TbPamPatentOaMapper dao;

    @Autowired
    private TbPamGeneralProcessTaskService tbPamGeneralProcessTaskService;

    @Autowired
    private TbPamPatentOaFileMapper tbPamPatentOaFileMapper;

    @Autowired
    private RoleKeyNameProperites roleKeyNameProperites;

    @Autowired
    private TbGlobalUserMapper userMapper;

    @Autowired
    private TbGlobalUserService tbGlobalUserService;


	/**
	 * 保存
	 * @author liuqinghua
	 * @date Jul 28, 2021 8:04:28 AM
	 */
    @Override
    public boolean save(TbPamPatentOa entity) {
        return super.save(entity);
    }

	/**
	 * 通过id获取数据
	 * @author liuqinghua
	 * @date Jul 28, 2021 8:04:28 AM
	 */
    @Override
    public TbPamPatentOa getById(Serializable id) {

        TbPamPatentOa byId = super.getById(id);
        if (byId != null) {
            QueryWrapper<TbGlobalUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_id",byId.getIpr());
            userQueryWrapper.eq("status",0);
            TbGlobalUser tbGlobalUser = userMapper.selectOne(userQueryWrapper);
            if(tbGlobalUser == null)
                byId.setIpr(null);
            List<TbPamPatentOaFile> list = tbPamPatentOaFileMapper.findListByDataId(id);
            byId.setFiles(list);
        }

        return byId;
    }

	/**
	 * 通过id删除数据
	 * @author liuqinghua
	 * @date Jul 28, 2021 8:04:28 AM
	 */
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

	/**
	 * 分页查询数据
	 * @author liuqinghua
	 * @date Jul 28, 2021 8:04:28 AM
	 */
    public IPage<TbPamPatentOa> selectPage(Map<String,Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        TbPamPatentOa entity = JSON.parseObject(JSON.toJSONString(data), TbPamPatentOa.class);
        Page<TbPamPatentOa> page = new Page(currentPage,pageSize);
        QueryWrapper<TbPamPatentOa> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

	/**
	 * 查询所有数据
	 * @author liuqinghua
	 * @date Jul 28, 2021 8:04:28 AM
	 */
    @Override
    public List<TbPamPatentOa> selectAll() {
        return super.selectAll();
    }


    public void startProcess(TbPamPatentOa data) throws Exception {

        this.save(data);
        List<TbPamPatentOaFile> files = data.getFiles();
        this.saveFiles(files, data.getId());

        Long ipr = data.getIpr();

        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        generalAuditVo.setDataId(data.getId());
        generalAuditVo.setUserIds(Arrays.asList(ipr));
        this.fillParams(generalAuditVo);
        tbPamGeneralProcessTaskService.startProcess(generalAuditVo, generalCallableVo -> {
            data.setNodeId(generalCallableVo.getNodeId());
            data.setNodeName(generalCallableVo.getNodeName());
            // 修改相关信息
            dao.updateById(data);
        });

    }

    private void saveFiles(List<TbPamPatentOaFile> files, Long dataId) {
        if (files.size() > 0) {

            tbPamPatentOaFileMapper.deleteByDataId(dataId);

            for (TbPamPatentOaFile file : files) {
                file.setPatentOaId(dataId);
                if (StringUtils.isBlank(file.getCreateBy())) {
                    file.setCreateBy(UserUtils.getLoginAppUser().getUserId());
                    file.setCreateDate(new Date());
                    file.setUpdateBy(UserUtils.getLoginAppUser().getUserId());
                    file.setUpdateDate(new Date());
                }
                tbPamPatentOaFileMapper.insert(file);
            }
        }
    }

    public void handleProcessNode(PatentOaAuditVo entity) throws Exception {

        Long nodeId = entity.getNodeId();

        // 组装审核数据
        GeneralAuditVo generalAuditVo = this.jointParams(entity);

        // 设置流程审核的用户或者角色
        this.setUserOrRole(entity, nodeId, generalAuditVo);


        TbPamPatentOa tbPamPatentOa = new TbPamPatentOa();
        tbPamPatentOa.setId(entity.getId());
        tbPamPatentOa.setIpr(entity.getIpr());
        // 处理流程
        tbPamGeneralProcessTaskService.handleProcess(generalAuditVo, generalCallableVo -> {
            tbPamPatentOa.setNodeId(generalCallableVo.getNodeId());
            tbPamPatentOa.setNodeName(generalCallableVo.getNodeName());

            if ("完结".equals(generalCallableVo.getNodeName())) {
                // TODO: 2021/8/2 修改授权通过
            }
            // 修改相关信息
            dao.updateById(tbPamPatentOa);
        });

        this.saveFiles(entity.getFiles(), entity.getId());

    }

    /***
     * 设置流程审核的用户或者角色
     * @author 苏小林
     * @date 2021/7/30 13:48
     * @param: entity
     * @param: nodeId
     * @param: generalAuditVo
     */
    private void setUserOrRole(PatentOaAuditVo entity, Long nodeId, GeneralAuditVo generalAuditVo) throws Exception {
        Integer status = entity.getStatus();
        String roleName;
        switch (nodeId.intValue()) {
            case 2: // 答复陈述书

                if (status == 0) { // 通过
                    roleName = roleKeyNameProperites.getZszl1();
//                    Long roleId = userMapper.getRoleIdByRoleKeyName(roleName);
//                    if (roleId == null) {
//                        throw new Exception("资深专利工程师角色不存在,请先完善角色。");
//                    }
                    // 根据角色名查找角色
                    List<Long> roleId = tbGlobalUserService.checkRole(roleName, "资深专利工程师");
                    // 检查角色下是否有用户
                    tbGlobalUserService.checkRoleUserId(roleName, "资深专利工程师");
                    generalAuditVo.setRoleIds(roleId);
                }
                break;
            case 3: // 知产部负责人审核
                if (status == 0) { // 通过
                    roleName = roleKeyNameProperites.getLedSeniorProcessEngineer();
//                    Long roleId = userMapper.getRoleIdByRoleKeyName(roleName);
//                    if (roleId == null) {
//                        throw new Exception("LED高级工艺工程师师角色不存在,请先完善角色。");
//                    }
                    // 根据角色名查找角色
                    List<Long> roleId = tbGlobalUserService.checkRole(roleName, "LED高级工艺工程师");
                    // 检查角色下是否有用户
                    tbGlobalUserService.checkRoleUserId(roleName, "LED高级工艺工程师");
                    generalAuditVo.setRoleIds(roleId);
//                    generalAuditVo.setRoleIds(Arrays.asList(roleId));
                } else if (status == 1) {
//                    TbPamPatentOa tbPamPatentOa = dao.selectById(entity.getId());
//                    Long ipr = tbPamPatentOa.getIpr();
                    generalAuditVo.setUserIds(Arrays.asList(entity.getIpr()));
                }
                break;
            case 4: // 研发负责人审核
                if (status == 0) { // 通过
                    roleName = roleKeyNameProperites.getGeneralManager();
//                    Long roleId = userMapper.getRoleIdByRoleKeyName(roleName);
//                    if (roleId == null) {
//                        throw new Exception("总经理角色不存在,请先完善角色。");
//                    }
                    // 根据角色名查找角色
                    List<Long> roleId = tbGlobalUserService.checkRole(roleName, "总经理");
                    // 检查角色下是否有用户
                    tbGlobalUserService.checkRoleUserId(roleName, "总经理");
                    generalAuditVo.setRoleIds(roleId);
//                    generalAuditVo.setRoleIds(Arrays.asList(roleId));
                } else if (status == 1) {
//                    TbPamPatentOa tbPamPatentOa = dao.selectById(entity.getId());
//                    Long ipr = tbPamPatentOa.getIpr();
//                    generalAuditVo.setUserIds(Arrays.asList(ipr));
                    generalAuditVo.setUserIds(Arrays.asList(entity.getIpr()));
                }
                break;
            case 5: // 总经理审核
                if (status == 0) { // 通过
                    roleName = roleKeyNameProperites.getAssistantName();
//                    Long roleId = userMapper.getRoleIdByRoleKeyName(roleName);
//                    if (roleId == null) {
//                        throw new Exception("流程专员角色不存在,请先完善角色。");
//                    }
                    // 根据角色名查找角色
                    List<Long> roleId = tbGlobalUserService.checkRole(roleName, "流程专员角色");
                    // 检查角色下是否有用户
                    tbGlobalUserService.checkRoleUserId(roleName, "流程专员角色");
                    generalAuditVo.setRoleIds(roleId);
//                    generalAuditVo.setRoleIds(Arrays.asList(roleId));
                } else if (status == 1) {
//                    TbPamPatentOa tbPamPatentOa = dao.selectById(entity.getId());
//                    Long ipr = tbPamPatentOa.getIpr();
//                    generalAuditVo.setUserIds(Arrays.asList(ipr));
                    generalAuditVo.setUserIds(Arrays.asList(entity.getIpr()));
                }
                break;
            case 6: // 流程专员递交
                roleName = roleKeyNameProperites.getAssistantName();
//                Long roleId = userMapper.getRoleIdByRoleKeyName(roleName);
//                if (roleId == null) {
//                    throw new Exception("流程专员角色不存在,请先完善角色。");
//                }
                // 根据角色名查找角色
                List<Long> roleId = tbGlobalUserService.checkRole(roleName, "流程专员角色");
                // 检查角色下是否有用户
                tbGlobalUserService.checkRoleUserId(roleName, "流程专员角色");
                generalAuditVo.setRoleIds(roleId);
//                generalAuditVo.setRoleIds(Arrays.asList(roleId));
                break;
            case 7: // 等待审查意见
                break;
        }
    }


    /**
     * 填充参数
     *
     * @author 苏小林
     * @date 2021/1/22 17:48
     * @param: generalAuditVo
     */
    private void fillParams(GeneralAuditVo generalAuditVo) {
        generalAuditVo.setProcessType("patent_oa");
        generalAuditVo.setNodeTableName("tb_pam_general_node");
        generalAuditVo.setTaskTableName("tb_pam_general_process_task");
        generalAuditVo.setHiTaskTableName("tb_pam_general_process_hi_task");
        generalAuditVo.setOpinionFileTableName("tb_pam_general_opinion_file");

    }

    private GeneralAuditVo jointParams(PatentOaAuditVo entity) {
        // 组装审核数据
        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        generalAuditVo.setNodeId(entity.getNodeId());
        generalAuditVo.setDataId(entity.getId());
        generalAuditVo.setProcessTaskId(entity.getProcessTaskId());
        generalAuditVo.setStatus(entity.getStatus());
        generalAuditVo.setOpinionText(entity.getOpinionText());
        generalAuditVo.setOpinionFiles(entity.getOpinionFiles());
        this.fillParams(generalAuditVo);
        return generalAuditVo;
    }


    public IPage<PatentOaRunTaskVo> findRunTask(FindRunTaskDto baseParam) throws Exception {

        // 查询正在执行中任务
        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        generalAuditVo.setUserIds(Arrays.asList(UserUtils.getLoginAppUser().getUserId()));
        List<Long> roleIds = userMapper.getRoleIdsByUserId(UserUtils.getLoginAppUser().getUserId());
        generalAuditVo.setRoleIds(roleIds);
        this.fillParams(generalAuditVo);
//        IPage<GeneralRunTaskVo> iPage = tbPamGeneralProcessTaskService.findRunTask(generalAuditVo);
//        List<GeneralRunTaskVo> runTask = iPage.getRecords();
        Page<PatentOaRunTaskVo> page = new Page<>(baseParam.getPage(), baseParam.getSize());
        IPage<PatentOaRunTaskVo> iPage = dao.findRunTask(page,generalAuditVo,baseParam);

        return iPage;
    }

    public IPage<PatentOaHiTaskVo> findHiTask(FindRunTaskDto baseParam) throws Exception {
        // 查询正在执行中任务
        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        generalAuditVo.setUserIds(Arrays.asList(UserUtils.getLoginAppUser().getUserId()));
        List<Long> roleIds = userMapper.getRoleIdsByUserId(UserUtils.getLoginAppUser().getUserId());
        generalAuditVo.setRoleIds(roleIds);
        this.fillParams(generalAuditVo);
//        IPage<GeneralRunTaskVo> iPage = tbPamGeneralProcessTaskService.findRunTask(generalAuditVo);
//        List<GeneralRunTaskVo> runTask = iPage.getRecords();
        Page<PatentOaHiTaskVo> page = new Page<>(baseParam.getPage(), baseParam.getSize());
        IPage<PatentOaHiTaskVo> iPage = dao.findHiTask(page,generalAuditVo,baseParam);

        return iPage;
    }

    public IPage<GeneralAuditHistoryVo> getAuditHistory(Long dataId, int page, int size) throws Exception {

        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        generalAuditVo.setPage(page);
        generalAuditVo.setSize(size);
        generalAuditVo.setDataId(dataId);
        this.fillParams(generalAuditVo);
        IPage<GeneralAuditHistoryVo> iPage = tbPamGeneralProcessTaskService.findAuditHistory(generalAuditVo);
        return iPage;
    }
}
